<template>
  <div class="w-full min-h-screen bg-gray-50">
    <main class="max-w-6xl mx-auto px-4 lg:px-8 py-8">
      <!-- 页面头部 -->
      <div class="mb-8">
        <div class="flex items-center gap-4">
          <button 
            @click="goBack"
            class="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            title="返回"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
            </svg>
          </button>
          <h1 class="text-2xl font-bold text-gray-900">创建自定义角色</h1>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧表单区域 -->
        <div class="flex-1 lg:max-w-4xl">
          <div class="bg-white rounded-2xl shadow-sm ring-1 ring-gray-200 p-8">
            <CharacterForm 
              v-model:form="form"
              @update:form="handleFormUpdate"
            />
          </div>
        </div>

        <!-- 右侧预览区域 -->
        <div class="lg:w-80 lg:flex-shrink-0">
          <div class="lg:fixed lg:top-24 lg:right-8 lg:w-80 lg:max-w-sm">
            <CharacterPreview :form="form" />
            
            <!-- 操作按钮 -->
            <div class="mt-6 space-y-3">
              <button 
                @click="handleSave"
                :disabled="!isFormValid"
                class="w-full h-12 px-6 rounded-lg bg-[#635BFF] text-white hover:bg-[#5a4fcf] disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
              >
                保存角色
              </button>
              
              <!-- 清空表单按钮 -->
              <button 
                @click="handleClearForm"
                class="w-full h-10 px-4 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors text-sm"
              >
                清空表单
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import CharacterForm from '@/components/create-role/CharacterForm.vue'
import CharacterPreview from '@/components/create-role/CharacterPreview.vue'
import { characterInfo } from '@/api'

// 本地存储的键名
const STORAGE_KEY = 'character-create-form'

// 表单数据
const form = ref({
  name: '',
  prompt: '',
  greeting: '',
  intro: '',
  voice: '',
  avatar: ''
})

// 从本地存储加载表单数据
const loadFormFromStorage = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      const parsed = JSON.parse(stored)
      form.value = { ...form.value, ...parsed }
      console.log('已从本地存储恢复表单数据:', form.value)
    }
  } catch (error) {
    console.error('加载本地存储数据失败:', error)
  }
}

// 保存表单数据到本地存储
const saveFormToStorage = () => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(form.value))
    console.log('已保存表单数据到本地存储:', form.value)
  } catch (error) {
    console.error('保存到本地存储失败:', error)
  }
}

// 清空本地存储
const clearFormStorage = () => {
  try {
    localStorage.removeItem(STORAGE_KEY)
    console.log('已清空本地存储')
  } catch (error) {
    console.error('清空本地存储失败:', error)
  }
}

// 表单验证
const isFormValid = computed(() => {
  return form.value.name.trim() !== '' && 
         form.value.prompt.trim() !== '' && 
         form.value.greeting.trim() !== ''
})

// 处理表单更新
const handleFormUpdate = (newForm: any) => {
  form.value = { ...newForm }
}

// 监听表单变化，自动保存到本地存储
watch(form, () => {
  // 使用防抖，避免频繁保存
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
  saveTimeout = setTimeout(() => {
    saveFormToStorage()
  }, 500)
}, { deep: true })

// 防抖定时器
let saveTimeout: ReturnType<typeof setTimeout> | null = null

// 页面加载时恢复数据
onMounted(() => {
  loadFormFromStorage()
})

// 页面卸载时清理定时器
onUnmounted(() => {
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
})

// 返回上一页
const goBack = () => {
  window.history.back()
}

// 清空表单
const handleClearForm = () => {
  if (confirm('确定要清空所有表单内容吗？此操作不可恢复。')) {
    form.value = {
      name: '',
      prompt: '',
      greeting: '',
      intro: '',
      voice: '',
      avatar: ''
    }
    clearFormStorage()
    alert('表单已清空')
  }
}

// 处理保存
const handleSave = async () => {
  if (!isFormValid.value) return
  
  try {
    console.log('保存角色:', form.value)
    
    // 调用创建角色API
    const response = await characterInfo.create({
      name: form.value.name,
      prompt: form.value.prompt,
      greeting: form.value.greeting,
      intro: form.value.intro,
      voice: form.value.voice,
      image: form.value.avatar
    })
    
    console.log('创建角色响应:', response)
    
    if (response.code === 0) {
      // 成功提示
      alert('角色创建成功！')
      // 清空本地存储
      clearFormStorage()
      // 跳转到自定义角色页面
      window.location.href = '/my?tab=custom-roles'
    } else {
      alert(`创建失败: ${(response as any).message || '未知错误'}`)
    }
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  }
}
</script>
